package com.trip.wechat.platform.subsystem.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.trip.wechat.platform.model.message.PushTemplateMessageResultBO;
import com.trip.wechat.platform.model.message.TemplateMessageBO;
import com.trip.wechat.platform.subsystem.TemplateMessageFacade;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.StringJoiner;

/**
 * 功能说明: <br>
 * 系统说明: <br>
 * 模块说明: <br>
 * 功能描述: <br>
 */
@Component("mp.templateMessage")
public class TemplateMessageFacadeMPImpl implements TemplateMessageFacade {

    final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Value("${mp.template_message.url:https://api.weixin.qq.com/cgi-bin/message/template/send}")
    protected String templateMessageUrl;

    @Autowired
    OkHttpClient httpClient;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public PushTemplateMessageResultBO push(String accessToken, TemplateMessageBO message) {
        if (Strings.isNullOrEmpty(accessToken)) {
            LOGGER.warn("[mp.templateMessage.push] accessToken cannot be empty!");
//            return createResult(CodeDict.C_SERVICE_FAIL, "accessToken is empty");
        }

        if (message == null || message.getData() == null
                || Strings.isNullOrEmpty(message.getTemplateId())
                || Strings.isNullOrEmpty(message.getToUser())) {
            LOGGER.warn("[mp.templateMessage.push] message invalid!");
//            return createResult(CodeDict.C_SERVICE_FAIL, "message invalid");
        }
        try {
            String body = objectMapper.writeValueAsString(message);
            LOGGER.debug("[mp.templateMessage.push] message => {}", body);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body);

            StringJoiner joiner = new StringJoiner("&", "?", "");
            joiner.add(Joiner.on("=").join("access_token", accessToken));

            Request request = new Request.Builder()
                    .url(templateMessageUrl + joiner.toString())
                    .post(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();

            String responseBody = response.body().string();
            return objectMapper.readValue(responseBody, PushTemplateMessageResultBO.class);
        } catch (JsonProcessingException e) {
            LOGGER.warn("[mp.templateMessage.push] message format failed! {}", e.getMessage());
//            return createResult(CodeDict.C_SERVICE_FAIL, "push failed");
        } catch (Exception e) {
            LOGGER.warn("[mp.templateMessage.push] {}! {}", e.getClass().getName(), e.getMessage());
//            return createResult(CodeDict.C_SERVICE_FAIL, "push failed");
        }
        return null;
    }

    protected PushTemplateMessageResultBO createResult(int code, String message) {
        PushTemplateMessageResultBO resultBO = new PushTemplateMessageResultBO();
        resultBO.setErrcode(code);
        resultBO.setErrmsg(message);
        return resultBO;
    }
}
